package com.dev.toolkit.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.dev.toolkit.common.enums.TypeConversionEnum;
import com.dev.toolkit.common.util.StrUtil2;
import com.dev.toolkit.domain.bo.ColumnBO;
import com.dev.toolkit.domain.bo.TableBO;
import com.dev.toolkit.model.ColumnModel;
import com.dev.toolkit.model.TableModel;
import com.dev.toolkit.service.IDataBaseMetaDataService;
import com.dev.toolkit.service.ITableDataService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author ZhuYouBin
 * @version 1.0.0
 * @date 2024/4/30 19:25
 * @description 表数据服务
 */
@Service
public class TableDataService implements ITableDataService {
    @Resource
    private IDataBaseMetaDataService dataBaseMetaDataService;

    @Override
    public List<TableBO> getTableList(String databaseName, String... tableNames) {
        List<TableModel> tableModelList = dataBaseMetaDataService.getTableModelList(databaseName, tableNames);
        if (CollectionUtil.isEmpty(tableModelList)) {
            return Collections.emptyList();
        }
        List<TableBO> tableList = new ArrayList<>();
        tableModelList.forEach(tableModel -> {
            tableList.add(getTableEntity(tableModel));
        });
        return tableList;
    }

    private static TableBO getTableEntity(TableModel tableModel) {
        TableBO table = new TableBO();
        table.setTableName(tableModel.getTableName());
        table.setTableRemark(tableModel.getTableRemark());
        table.setClassName(StrUtil2.getJavaClassName(tableModel.getTableName(), null, null));
        table.setSmallClassName(StrUtil2.firstCharToLowerCase(table.getClassName()));

        // 设置列字段
        List<ColumnBO> columns = new ArrayList<>();
        List<ColumnModel> columnList = tableModel.getColumnModelList();
        columnList.forEach(columnModel -> {
            ColumnBO column = new ColumnBO();
            column.setColumnName(columnModel.getColumnName());
            column.setColumnRemark(columnModel.getColumnRemark());
            column.setFiledName(StrUtil2.getFieldName(columnModel.getColumnName()));
            column.setFiledType(TypeConversionEnum.getValueByCode(columnModel.getTypeName()));
            column.setAutoIncrement(columnModel.isAutoIncrement());
            column.setPrimaryKey(columnModel.isPrimaryKey());
            columns.add(column);
        });
        table.setColumns(columns);
        return table;
    }

}